package com.atguigu.cloud.user.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.atguigu.cloud.user.entity.User;
import com.atguigu.cloud.user.properties.PatternProperties;
import com.atguigu.cloud.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * Nacos配置中心热更新：@RefreshScope
 *
 * @author Taeyang
 * @date 2025/4/4
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/user")
@RefreshScope
public class UserController {

    @Autowired
    private UserService userService;

    @Value("${pattern.dateformat}")
    private String pattern;

    @Autowired
    private PatternProperties patternProperties;

    /**
     * 热点资源 @SentinelResource("hot")
     *
     * @param userId
     * @param token
     * @param header
     * @return
     */
    @SentinelResource("hot")
    @GetMapping(value = "/findUserByUserId/{userId}")
    public User findUserByUserId(
            @PathVariable(value = "userId") Long userId,
            @RequestHeader(name = "token", required = false) String token,
            @RequestHeader(name = "Truth", required = false) String header
    ) {

        log.info("findUserByUserId请求头 token：" + token);
        log.info("findUserByUserId请求头 Truch：" + header);

        System.out.println("pattern:" + pattern);
        System.out.println("patternProperties:" + patternProperties.getDateformat());

        // try {
        //     // 休眠60ms
        //     TimeUnit.MILLISECONDS.sleep(60);
        // } catch (InterruptedException e) {
        //     throw new RuntimeException(e);
        // }

        if(userId == 2){
            throw new RuntimeException("手动抛出异常") ;
        }

        return userService.getById(userId);
    }

    /**
     * 修改用户数据端点
     */
    @GetMapping(value = "/updateUserById")
    public String updateUserById() {
        return "修改用户数据成功";
    }

    /**
     * 保存用户
     *
     * @return
     */
    @GetMapping(value = "/save")
    public String save() {
        userService.queryUsers("save...");
        System.out.println("保存用户");
        return "保存用户成功";
    }

    /**
     * 查询用户
     *
     * @return
     */
    @GetMapping(value = "/query")
    public String query() {
        userService.queryUsers("query...");
        System.out.println("查询用户");
        return "查询用户成功";
    }

}
